package com.yuerlive.rainbow.common;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.NetUtil;

import java.util.ArrayList;

/**
 * Created by Admin on 2017/6/14.
 */

public class NetBroadcastReceiver extends BroadcastReceiver {
    public static ArrayList<NetEventHandler> mListeners;
    private static String NET_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

    @Override
    public void onReceive(Context context, Intent intent) {
        // 如果相等的话就说明网络状态发生了变化
        L.e("NetBroadcastReceiver", "onReceive");
        if (intent.getAction().equals(NET_CHANGE_ACTION)) {
            int netWorkState = NetUtil.getNetworkState(context);
            L.e("NetBroadcastReceiver", "onReceive" + netWorkState);
            // 接口回调传过去状态的类型
            if (mListeners != null && mListeners.size() > 0)// 通知接口完成加载
                mListeners.get(Math.max(0, mListeners.size() - 1)).onNetChange(netWorkState);
        }
    }

    public static void addListener(NetEventHandler listener) {
        if (mListeners == null) {
            synchronized (NetBroadcastReceiver.class) {
                if (mListeners == null) {
                    mListeners = new ArrayList<>();
                }
            }
        }
        mListeners.add(listener);
    }

    public static void removeListener(NetEventHandler listener) {
        if (mListeners == null) return;
        if (mListeners.contains(listener)) {
            mListeners.remove(listener);
            listener = null;
        }
    }

    public static void removeAllListener() {
        if (mListeners == null) return;
        mListeners.clear();
        mListeners = null;
    }

    public static interface NetEventHandler {

        public void onNetChange(int netWorkState);
    }
}
